package com.itheima.store.web.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.itheima.store.domain.Dept;
import com.itheima.store.domain.PageBean;
import com.itheima.store.domain.Post;
import com.itheima.store.domain.User;
import com.itheima.store.service.DeptManagerService;
import com.itheima.store.service.PostManagerService;
import com.itheima.store.service.UserService;
import com.itheima.store.utils.BaseServlet;
import com.itheima.store.utils.BeanFactory;
import com.itheima.store.utils.UUIDUtils;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class AdminUserServlet
 */
public class AdminUserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    //查询所有用户的,返回跳转到list.jsp
	
	public String findUserAll(HttpServletRequest req , HttpServletResponse resp) {
		//获取UserService实例对象
		UserService userService = (UserService) BeanFactory.getBean("userService");
		List<User> list;
		try {
			list = userService.findUserAll();
			req.setAttribute("list", list);
			return "/admin/user/list.jsp";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("查询所有用户出现了错误！");
		}
		
		
	}
	
	 //查询所有用户的，通过分页的形式,返回跳转到list.jsp
	
		public String findUserAllPageBean(HttpServletRequest req , HttpServletResponse resp) {
			//获取UserService实例对象
			int currPage = Integer.parseInt(req.getParameter("currPage"));
			//获取search参数，如果参数为空的话，在Dao层就用动态SQL执行查询
			String search = req.getParameter("search");
			UserService userService = (UserService) BeanFactory.getBean("userService");
			try {
				//为了公用list页面，需要在超链接后面增加search参数（因为超链接的提价方式默认是get ）所以把这个search字段存放的request域中。
				req.setAttribute("search", search);
				PageBean<User> pageBean = userService.findUserAllPageBean(currPage,search);
				req.setAttribute("pageBean", pageBean);
				return "/admin/user/list.jsp";
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("查询所有用户出现了错误！");
			}
			
			
			
		}
		
		//编辑用户,根据用户ID来编辑用户
		public String edit(HttpServletRequest req , HttpServletResponse resp) {
			String uid = req.getParameter("uid");
			//1.根据用户ID查询到用户实体
			UserService userService = (UserService) BeanFactory.getBean("userService");
			User existUser;
			try {
				existUser = userService.findUserByUid(uid);
				if(existUser != null) {
					req.setAttribute("user", existUser);
					return "/admin/user/edit.jsp";
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
		}
		
		
		//保存修改后后的用户
		public String saveUser(HttpServletRequest req ,HttpServletResponse resp) {
			try {
				req.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Map<String, String[]> map = req.getParameterMap();
			User user = new User();
			String name = req.getParameter("user_name");
			
			try {
				name =new String(name.getBytes("ISO8859-1"), "UTF-8") ;
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				BeanUtils.populate(user, map);
				System.out.println(user.toString());
				UserService userService =(UserService)BeanFactory.getBean("userService");
				try {
					userService.updateEdit(user);
					try {
						resp.sendRedirect(req.getContextPath()+"/AdminUserServlet?method=findUserAllPageBean&currPage=1");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (IllegalAccessException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		//修改用户锁定状态(ajax方式)
		public String lockUser(HttpServletRequest req ,HttpServletResponse resp) {
			//1.获取UID 及lock参数
			try {
			String uid = req.getParameter("uid");
			String lock = req.getParameter("lock");
			//2.获取userService
			UserService userService  = (UserService) BeanFactory.getBean("userService");
			userService.lockUser(uid,lock);
			User existUser = userService.findUserByUid(uid);
			lock = existUser.getIsforbidden();
			resp.getWriter().println(lock);
			System.out.println(lock);
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				throw new RuntimeException();
			}
			
			return null;
		}
		
		
		//删除用户
		public String delUser(HttpServletRequest req ,HttpServletResponse resp) {
			
			try {
				String uid = req.getParameter("uid");
				String lock = req.getParameter("lock");
				//2.获取userService
				UserService userService  = (UserService) BeanFactory.getBean("userService");
				userService.delUser(uid);
				resp.sendRedirect(req.getContextPath()+"/AdminUserServlet?method=findUserAllPageBean&currPage=1");
				
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw new RuntimeException();
				}
				
				return null;
			}

		
		//后台用户模块添加用户
		public String addUser(HttpServletRequest req,HttpServletResponse resp) {
			User user = new User();
			//新增一个部门
			Dept dept = new Dept();
			//新增一个职位
			Post post  = new Post();
			Map<String, String[]> map = req.getParameterMap();
			try {
				BeanUtils.populate(dept, map);
				BeanUtils.populate(post, map);
				user.setDept(dept);
				user.setPost(post);
				User existUserAdmin = (User) req.getSession().getAttribute("existUserAdmin");
				if(existUserAdmin ==null) {
					req.setAttribute("msg", "用户还没有登录！");
					return "/admin/index.jsp";
				}
				user.setCreatePerson_id(existUserAdmin.getUser_id());
				user.setCreatePerson_name(existUserAdmin.getUser_name());
				//需要填充User对象的属性
				String user_id = UUIDUtils.getUUID();
				BeanUtils.populate(user, map);
				
				//添加当前时间为用户操作时间
				user.setCreateTime(new Date(System.currentTimeMillis()));
				user.setUser_id(user_id);
				UserService userService =  (UserService) BeanFactory.getBean("userService");
				try {
					List<User> userByUserName = userService.findByUsername(user.getUser_name());
					if(userByUserName.size() !=0) {
						int numB = 0;
						String user_name = user.getUser_name();
						String num = user.getUser_name().substring(user_name.length()-1);
						//如果有异常则说明姓名在数据库中不存在 姓名1  姓名2的这种情况
						try {
						numB =	Integer.parseInt(num);
							
						}catch (Exception e) {
							// TODO: handle exception
							
						}
						
//						if(!"".equals(num)) {
//							numB = Integer.parseInt(num);
//						}
						int lastNum = numB+userByUserName.size();
						req.setAttribute("msg", "这个用户的姓名有重名的!请在姓名后面填写数字"+lastNum);
						return "/admin/user/add.jsp";
					}
					userService.add(user);
					try {
						resp.sendRedirect(req.getContextPath()+"/AdminUserServlet?method=findUserAllPageBean&currPage=1");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					throw new RuntimeException("添加用户错误❌");
				}
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return null;
		
		}
		
			
		//添加后台登录功能 
		public String loginAdmin(HttpServletRequest req,HttpServletResponse resp) {
			Map<String, String[]> map = req.getParameterMap();
			User user = new User();  
			try {
				BeanUtils.populate(user, map);
				UserService userService =  (UserService) BeanFactory.getBean("userService");
				User existUserAdmin =userService.loginAdmin(user);
				if(existUserAdmin!= null) {
					//把用户保存到Session域对象中
					req.getSession().setAttribute("existUserAdmin", existUserAdmin);
					return "/admin/home.jsp"; 
				}else {
					req.setAttribute("msg", "用户名或密码不正确！");
					return "/admin/index.jsp";
				}
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				throw new RuntimeException("后台登录粗线问题！");
			}
			
		}
		
		//退出登录
		public String loginOut(HttpServletRequest req,HttpServletResponse resp) {

			try {
				// 销毁session
				req.getSession().invalidate();
				
				
				resp.sendRedirect(req.getContextPath()+"/admin/index.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		/**
		 * 动态获取职位信息
		 * @param req
		 * @param resp
		 * @return
		 */
		public String ajaxPost(HttpServletRequest req,HttpServletResponse resp) {
			PostManagerService postManagerService =(PostManagerService)BeanFactory.getBean("postManagerService");
			try {
				List<Post> list = postManagerService.findAllPost();
				JSONArray listJson = JSONArray.fromObject(list);
				try {
					System.out.println(listJson.toString());
					resp.getWriter().print(listJson.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
		}
		
		/**
		 * 动态获取部门信息
		 * @param req
		 * @param resp
		 * @return
		 */
		public String ajaxDept(HttpServletRequest req,HttpServletResponse resp) {
			DeptManagerService deptManagerService =(DeptManagerService)BeanFactory.getBean("deptManagerService");
			try {
				List<Dept> list = deptManagerService.findAllDept();
				JSONArray listJson = JSONArray.fromObject(list);
				try {
					System.out.println(listJson.toString());
					resp.getWriter().print(listJson.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
		}
		
		}


		
		
		
		
		
		
		
		
		
		


